<?php

class Session
{
	const db_host = "127.0.0.1";
	const db_user = "redfox";
	const db_pwd = "redfox@401";
	const db_name = "test";
	const db_table = "tbl_session";
	private $db_handle;
	private $lifeTime;

	function open($savePath, $sessName)
	{
		$this->lifeTime = get_cfg_var("session.gc_maxlifetime");
		$db_handle = @mysql_connect(self::db_host, self::db_user, self::db_pwd);
		$dbSel = @mysql_select_db(self::db_name, $db_handle);
		if (!$db_handle || !$dbSel) return false;
		$this->db_handle = $db_handle;
		return true;
	}

	function close()
	{
		$this->gc(ini_get('session.gc_maxlifetime'));
		return @mysql_close($this->db_handle);
	}

	function read($sessID)
	{
		$res = @mysql_query("SELECT session_data AS d FROM " . self::db_table . "
            WHERE session_id = '$sessID'
            AND session_expires > " . time(), $this->db_handle);
		if ($row = @mysql_fetch_assoc($res)) return $row['d'];
		return "";
	}

	function write($sessID, $sessData)
	{
		$newExp = time() + $this->lifeTime;
		$res = @mysql_query("SELECT * FROM " . self::db_table . "
            WHERE session_id = '$sessID'", $this->db_handle);
		if (@mysql_num_rows($res)) {
			@mysql_query("UPDATE " . self::db_table . "
                SET session_expires = '$newExp',
                session_data = '$sessData'
                WHERE session_id = '$sessID'", $this->db_handle);
			if (@mysql_affected_rows($this->db_handle)) return true;
		} else {
			@mysql_query("INSERT INTO " . self::db_table . " (
                session_id,
                session_expires,
                session_data)
                VALUES(
                    '$sessID',
                    '$newExp',
                    '$sessData')", $this->db_handle);
			if (@mysql_affected_rows($this->db_handle)) return true;
		}
		return false;
	}

	function destroy($sessID)
	{
		@mysql_query("DELETE FROM " . self::db_table . " WHERE session_id = '$sessID'", $this->db_handle);
		if (@mysql_affected_rows($this->db_handle)) return true;
		return false;
	}

	function gc($sessMaxLifeTime)
	{
		@mysql_query("DELETE FROM " . self::db_table . " WHERE session_expires < " . time(), $this->db_handle);
		return @mysql_affected_rows($this->db_handle);
	}
}

define("MAIN_DOMAIN", ".oauth.com");
define("COOKIE_DOMAIN", true);
if (defined("COOKIE_DOMAIN") && COOKIE_DOMAIN) {
	if (defined("MAIN_DOMAIN")) @ini_set("session.cookie_domain", MAIN_DOMAIN);
}
define("USER_SESSION", false);
if (defined("USER_SESSION") && USER_SESSION) {
	@ini_set("session.save_handler", "user");
	$session = new Session;
	@session_module_name("user");
	@session_set_save_handler(array(&$session, "open"), array(&$session, "close"), array(&$session, "read"), array(&$session, "write"), array(&$session, "destroy"), array(&$session, "gc"));
}
@session_start(); ?>